package com.dao;


import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;
import javax.transaction.TransactionManager;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


import com.model.Branch;
import com.model.Member;
import com.service.BranchService;

@Repository("memberDao")
public class MemberDaoImpl implements MemberDao {

	@Autowired
	private SessionFactory sessionFactory;
	@Autowired
	private BranchService branchService;
	
	public Session getSession()
	{
		return sessionFactory.getCurrentSession();
	}
	public Member get(Integer id) {
		return (Member)getSession().get(Member.class, id);	
	}

	public void add(String branch,Member member) {
		member.setBranch(branchService.findByName(branch));	 
		getSession().save(member);
}

	public void delete(Integer memberID){

		Member member= (Member) getSession().get(Member.class, memberID);
			getSession().delete(member);
	}


	@SuppressWarnings("unchecked")
	public List<Member> getAllForUser(String name) {
		return getSession().createCriteria(Member.class)
				.createAlias("branch", "b")
				.add(Expression.eq("b.branchName",name))
				.list();
	}
	@SuppressWarnings("unchecked")
	public List<Member> getAllForAdmin(){
		return (List<Member>) getSession().createCriteria(Member.class).list();	
	}
	@SuppressWarnings("unchecked")
	public List<Member> getByFields(Integer id,String ticket,Date from,Date to,String name)
	{
		Criteria criteria = getSession().createCriteria(Member.class);
		if(id!=0)
			criteria.add(Expression.eq("memberId", new Integer(id)));
		if(!ticket.isEmpty())
			criteria.add(Expression.eq("ticketNo",ticket));
		if (from != null) {
			criteria.add(Expression.ge("joinDate",from));
		}
		if (!(name.equals("select Branch"))) {
			criteria.createAlias("branch", "b");
			criteria.add(Expression.eq("b.branchName",name));
		}
		if (to != null) {
			criteria.add(Expression.le("joinDate",to));
		}
		return criteria.list();
	}
	
	@SuppressWarnings("unchecked")
	public List<Member> getAll(int page) {
		return getSession().createCriteria(Member.class) 
				.addOrder(Order.desc("memberId"))
				.setFirstResult((page-1) * 5).setMaxResults(5).setFetchSize(5)
				.list(); 
				
		 
	    
	}
	public int getNoOfRecords() {
		return ((Number) getSession().createQuery("select count(*) from Member").uniqueResult()).intValue();
		
    }
}
